package chapter02.part03;

import lombok.Getter;
import lombok.ToString;

import java.io.*;
import java.time.LocalDate;

/**
 * 使用一次序列化和反序列化来达成和克隆相同的作用
 * 
 * 缺点是更慢
 * 
 * @author insight
 * @since 2021/8/17
 */
public class SerialCloneTest {
    public static void main(String[] args) {
        Employee fuu = new Employee("fuu", 40000, 1990
                , 3, 15);

        Object newFuu = fuu.clone();
        fuu.raiseSalary(100);

        System.out.println(fuu);
        System.out.println(newFuu);
    }

    @Getter
    @ToString
    public static class Employee implements Serializable {
        public static final int NAME_SIZE = 5;
        public static final int RECORD_SIZE = NAME_SIZE * 2 + 20;

        private String name;
        private double salary;
        private LocalDate hireDay;

        public Employee(String name, double salary, int year, int month, int day) {
            this.name = name;
            this.salary = salary;
            this.hireDay = LocalDate.of(year, month, day);
        }
        
        public void raiseSalary(double raise) {
            this.salary += raise;
        }
        
        @Override
        public Object clone() {
            try {
                ByteArrayOutputStream bout =
                        new ByteArrayOutputStream();
                
                try (ObjectOutputStream out =
                             new ObjectOutputStream(bout)) {
                    out.writeObject(this);
                }
                
                try (ByteArrayInputStream bin =
                             new ByteArrayInputStream(bout.toByteArray())) {
                    ObjectInputStream in =
                            new ObjectInputStream(bin);
                    return in.readObject();
                }
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
            return null;
        }
    }
    
}